<?php


namespace app\socket\services;


use app\common\model\MemberLogs;
use app\common\model\MessageLogModel;
use app\common\model\UserListModel;
use app\common\services\RedisService;
use GatewayWorker\Lib\Gateway;

class BaseService
{

    static public $kefuRole = '1_'; //客服role级别
    static public $kehuRole = '2_'; //客户role级别

    //客服所在前缀
    static public $companyKey = 'company_list:';
    //顾客所在房间前缀
    static public $roomKey = 'room_list:';

    /**
     * Gateway::bindUid(string $client_id, mixed $uid);  将$client_id 和 uid绑定 以便通过Gateway::sendToUid($uid)
     * Gateway::isOnline(string $client_id);  通过$client_id查询是否在线
     * Gateway::isUidOnline(mixed $uid);  通过$uid 查询是否在线
     * Gateway::getClientIdByUid(mixed $uid); 通过uid 拿到对应的所有 client_id
     * Gateway::getUidByClientId(string $client_id); 通过client_id 拿到对应的 uid
     *
     * Gateway::sendToUid(uid,message)   //向uid 绑定的所有在线的client_id 发送数据
     *
     * Gateway::joinGroup(string $client_id, mixed $group); // 将 client_id 加入某个组
     * Gateway::ungroup(mixed $group);  // 解散某个分组
     * Gateway::leaveGroup(string $client_id, mixed $group); // 将某个连接 从某个分组踢出
     * Gateway::sendToGroup(mixed $group, string $message [, array $exclude_client_id = null [, bool $raw = false]]);  给某个分组发消息
     *
     */



    /**
     * 发送消息
     * @param $type  消息类型
     * @param $data  消息数据
     * @param false $client_id  接收人 没有的情况下 发送给当前用户
     */
    public static function success(array $data,$uid=false){
//        $data['type'] = $type;
        //发送给指定用户
        if($uid){
            //给自己的其他客户端进行推送
            if(in_array($data['type'],['say','system'])){
                //加入聊天记录中
                $data['id'] = MessageLogModel::addMessage($data);

                $client_list = Gateway::getClientIdByUid(self::getUUid2());
                if(count($client_list)>1){
                    foreach ($client_list as $client_id){
                        if($client_id != $_SESSION['client_id']){
                            $data['type']='my_say';
                            Gateway::sendToClient($client_id, json_encode($data,320));
                        }
                    }
                }
            }

//            $uuid = self::getUUid($uid);
            $msg_data = json_encode($data,320);
            //给指定的用户发送消息
            Gateway::sendToUid($uid,$msg_data);
        }else{
            $msg_data = json_encode($data,320);
//            dump('消息返回自身');
//            dump($msg_data);
            Gateway::sendToCurrentClient($msg_data);
        }
    }

    /**
     * 返回处理后的uid
     * 获取 对方uid时使用
     * @param $uid
     * @return mixed|string
     */
    public static function getUUid($uid){
//        dump($_SESSION);
        if(!strpos($uid.'','_')){
            if($_SESSION['userinfo']['role']==1){
                //客服发消息 默认发送对象为 客户
                $uid = self::$kehuRole.$uid;
            }else{
                $uid = self::$kefuRole.$uid;
            }
        }
        return $uid;
    }

    /**
     * 获取自己的uid时使用
     * @param $uid
     * @return mixed|string
     */
    public static function getUUid2(){
        $uid = $_SESSION['userinfo']['id'];
        if(!strpos($uid.'','_')){
            if($_SESSION['userinfo']['role']==2){
                //客服发消息 默认发送对象为 客户
                $uid = self::$kehuRole.$uid;
            }else{
                $uid = self::$kefuRole.$uid;
            }
        }
        return $uid;
    }

    /**
     * 将双方加入到房间中
     * @param $uuid1
     * @param $uuid2
     */
    static public function joinRoom($uuid1,$uuid2){
        $clientArr1 = Gateway::getClientIdByUid($uuid1);
        $clientArr2 = Gateway::getClientIdByUid($uuid2);

        //将我加入对方的房间中
        foreach ($clientArr1 as $client_id){
            Gateway::joinGroup($client_id, self::$roomKey.$uuid2);
        }

        //将对方加入我的房间中
        foreach ($clientArr2 as $client_id){
            Gateway::joinGroup($client_id, self::$roomKey.$uuid1);
        }

        //将双方互加好友列表
        UserListModel::addUser($uuid2,$uuid1);
    }

    /**
     * 通知大家 我上线了
     */
    static public function popUpOnline($userInfo){
        $msg_data = [
            'type'=>'Online',
            'online'=>1,
            'uuid'=>$userInfo['uuid'],
        ];
        Gateway::sendToGroup(BaseService::$roomKey.$userInfo['uuid'],json_encode($msg_data));
    }

    /**
     * 通知大家  我离线了
     * @param $userInfo
     */
    static public function popOffLine($userInfo){
        $msg_data = [
            'type'=>'offline',
            'online'=>0,
            'uuid'=>$userInfo['uuid'],
        ];
        Gateway::sendToGroup(BaseService::$roomKey.$userInfo['uuid'],json_encode($msg_data));
    }

    /**
     * 处理用户信息  转化为 适合前端的数据格式
     * @param $userInfo  需要处理的用户信息
     * @param int $toId  信息接收人id
     * @return array
     */
    static public function handleUserInfo($userInfo,$toId=0){
        $headimg = @($userInfo['headimg'] ? $userInfo['headimg'] : $userInfo['head']);
        $userInfo['last'] = [];
        $toId = $toId ?: $_SESSION['userinfo']['id'];
        $hasNewMsg = 0;
        //获取最后一条聊天记录
        if($userInfo['uuid'] != $toId){
            $userInfo['last'] = MessageLogModel::getLastMsg($userInfo['uuid'],$toId);
            $hasNewMsg = MessageLogModel::findCount(['from_user_id'=>$userInfo['uuid'],'to_user_id'=>$_SESSION['userinfo']['uuid'],'is_reda'=>1]);
        }
        $newUserInfo = [
            'id'=>$userInfo['id'],
//            'uuid'=>$userInfo['role'].'_'.$userInfo['id'],
            'uuid'=>$userInfo['uuid'],
            'nickname'=>$userInfo['name'],
            'mobile'=>$userInfo['mobile'],
            'headimg'=>$headimg,
            'active'=>false,
            'hasNewMsg'=>$hasNewMsg,//消息数,
            'role'=>$userInfo['role'],
            'last_id'=>isset($userInfo['last']['id'])?$userInfo['last']['id']:-1,
        ];
        $newUserInfo['online'] = Gateway::isUidOnline($newUserInfo['uuid']);
        $newUserInfo['append'] = array_diff_key($userInfo,$newUserInfo);

        return $newUserInfo;
    }

    /**
     * 发送消息
     * @param $type  消息类型
     * @param $data  消息数据
     * @param false $client_id  接收人 没有的情况下 发送给当前用户
     */
    public static function success2($type,$data,$client_id=false){
        $data['type'] = $type;

        //发送给指定用户
        if($client_id){
            Gateway::sendToClient($client_id, json_encode($data,320));
        }else{
            //发送给 自己
            Gateway::sendToCurrentClient(json_encode($data,320));
        }
    }


    public static function debug($text){
        if(is_array($text)){
            echo "debug ===> ".json_encode($text)."\n";
        }else{
            echo "debug ===> {$text} \n";

        }
    }
}